// LiveKit 控制器应用 - 集成项目信息获取和消息协议
// import { DataTopic, DataCommand } from './message-types.js';

class ControllerApp {
  constructor() {
    this.room = null;
    this.roomName = null;
    this.participantName = 'controller';
    this.activeTab = 'flow';
    this.messages = [];
    this.projectId = null;
    this.projectInfo = null;
    this.flowNodes = [];
    this.livekitConfig = null;
    this.selectedFlowNode = null;
    
    this.init();
  }

  async init() {
    this.showConnecting();
    
    // 从URL参数获取项目ID和房间名
    const urlParams = new URLSearchParams(window.location.search);
    this.projectId = urlParams.get('projectId') || urlParams.get('id');
    // this.roomName = urlParams.get('room') || 'guide-room';
    
    if (!this.projectId) {
      this.showError('缺少项目ID参数');
      return;
    }
    
    try {
      // 1. 获取项目信息
      await this.fetchProjectInfo();
      
      // 2. 检查项目类型是否为guide
      if (this.projectInfo?.projectSet?.platform !== 'guide') {
        this.showError('当前项目类型不是guide模式，无法使用控制端');
        return;
      }
      
      // 3. 获取LiveKit配置
      await this.getLiveKitConfig();
      
      // 4. 加载流程节点
      this.loadFlowNodes();
      
      // 5. 连接到LiveKit房间
      await this.connectToRoom();
      
      this.hideConnecting();
      this.setupUI();
      
      // 加载聊天记录
      this.loadChatHistory();
      
    } catch (error) {
      console.error('初始化失败:', error);
      this.showError(`初始化失败: ${error.message}`);
    }
  }

  async fetchProjectInfo() {
    try {
      // 严格遵循apiRequst.ts中的完整路径
      // 获取当前访问地址的域名和端口号
      const currentOrigin = window.location.origin;
      const apiUrl = `${currentOrigin}/aihuman/api/aihuman-coreBusiness/aimetaProjectManager/getProjectAllConfigInfo`;
      const response = await fetch(apiUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json;charset=utf-8',
          'Access-Control-Allow-Origin': '*',
        },
        body: JSON.stringify({
          id: this.projectId
        })
      });
      
      if (!response.ok) {
        throw new Error('获取项目信息失败');
      }
      
      const result = await response.json();
      this.projectInfo = result.data;
      console.log('项目信息:', this.projectInfo);
    } catch (error) {
      console.error('获取项目信息失败:', error);
      throw error;
    }
  }

  async getLiveKitConfig() {
    try {
      // 严格遵循renderContainer中的API调用方式 - getTokenToBegin
      const currentOrigin = window.location.origin;
      const apiUrl = `${currentOrigin}/aihuman/api/aihuman-engine/coreRobot/begin`;
      const response = await fetch(apiUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json;charset=utf-8',
          'Access-Control-Allow-Origin': '*',
        },
        body: JSON.stringify({
          configJson: this.projectInfo,
          clientType: 4 // 控制器客户端类型
        })
      });
      
      if (!response.ok) {
        throw new Error('获取LiveKit配置失败');
      }
      
      const result = await response.json();
      const serverInfo = result.data;
      
      this.livekitConfig = {
        url: serverInfo.wsServer.url,
        token: serverInfo.wsServer.token,
      };
      
      console.log('LiveKit配置:', this.livekitConfig);
    } catch (error) {
      console.error('获取LiveKit配置失败:', error);
      throw error;
    }
  }

  loadFlowNodes() {
    if (this.projectInfo?.flowNodeConfig) {
      this.flowNodes = this.projectInfo.flowNodeConfig;
    } 
  }

  getIconForNode(node) {
    // 根据节点名称智能选择图标
    const name = node.name.toLowerCase();
    if (name.includes('欢迎')) return '👋';
    if (name.includes('介绍')) return '📖';
    if (name.includes('演示')) return '🎬';
    if (name.includes('问题')) return '❓';
    return '📝';
  }

  async connectToRoom() {
    
    this.room = new LivekitClient.Room({
      adaptiveStream: true,
      dynacast: true,
      videoCaptureDefaults: {
        resolution: LivekitClient.VideoPresets.h720.resolution,
      }
    });
    
    // 监听房间事件
    this.room
      .on(LivekitClient.RoomEvent.DataReceived, (payload, participant, kind, topic) => {
        this.handleDataMessage(payload, participant, kind, topic);
      })
      .on(LivekitClient.RoomEvent.ParticipantConnected, (participant) => {
        console.log('参与者加入:', participant.identity);
        this.addSystemMessage(`${participant.identity} 加入了房间`);
      })
      .on(LivekitClient.RoomEvent.ParticipantDisconnected, (participant) => {
        console.log('参与者离开:', participant.identity);
        this.addSystemMessage(`${participant.identity} 离开了房间`);
      })
      .on(LivekitClient.RoomEvent.Disconnected, () => {
        console.log('已断开连接');
        this.addSystemMessage('与服务器断开连接');
      });

    await this.room.connect(this.livekitConfig.url, this.livekitConfig.token);
    // console.log('已连接到房间:', this.roomName);
    
    // 发送控制器加入消息
    // this.sendControllerMessage({
    //   type: 'controller_join',
    //   data: { 
    //     projectId: this.projectId,
    //     timestamp: Date.now()
    //   }
    // });
  }


  setupUI() {
    // 渲染流程节点
    this.renderFlowNodes();
    
    // 设置默认活动tab
    this.switchTab('flow');
    
    // Tab切换事件已在 enhanced-interactions.js 中设置
    // 这里不再重复添加事件监听器

    // 发送消息
    const sendBtn = document.getElementById('sendBtn');
    const messageInput = document.getElementById('messageInput');
    
    sendBtn.addEventListener('click', () => {
      this.sendChatMessage();
    });
    
    messageInput.addEventListener('keypress', (e) => {
      if (e.key === 'Enter') {
        this.sendChatMessage();
      }
    });

    // 麦克风按钮事件
    const micButton = document.getElementById('micButton');
    
    // 触摸事件
    micButton.addEventListener('touchstart', (e) => {
      e.preventDefault();
      this.startRecording();
    });
    
    micButton.addEventListener('touchend', (e) => {
      e.preventDefault();
      this.stopRecording();
    });
    
    // 鼠标事件（桌面端）
    micButton.addEventListener('mousedown', () => {
      this.startRecording();
    });
    
    micButton.addEventListener('mouseup', () => {
      this.stopRecording();
    });
    
    micButton.addEventListener('mouseleave', () => {
      this.stopRecording();
    });

    // 清空聊天记录按钮
    const clearChatBtn = document.getElementById('clearChatBtn');
    if (clearChatBtn) {
      clearChatBtn.addEventListener('click', () => {
        if (confirm('确定要清空所有聊天记录吗？')) {
          this.clearChatHistory();
        }
      });
    }

    // 显示主界面
    document.getElementById('app').style.display = 'flex';
  }

  renderFlowNodes() {
    const flowList = document.getElementById('flowList');
    flowList.innerHTML = '';
    
    this.flowNodes.forEach((node, index) => {
      const flowItem = document.createElement('div');
      flowItem.className = 'flow-item';
      flowItem.setAttribute('data-node-id', node.id);
      
      // 如果这个节点是当前选中的节点，添加selected类
      if (this.selectedFlowNode && this.selectedFlowNode.id === node.id) {
        flowItem.classList.add('selected');
      }
      
      // 调试信息：检查是否有默认选中
      console.log(`Flow node ${index}: ${node.name}, selected: ${this.selectedFlowNode && this.selectedFlowNode.id === node.id}`);
      
      flowItem.innerHTML = `
        <div class="flow-info">
          <div class="flow-name">${node.name}</div>
        </div>
      `;
      
      flowItem.addEventListener('click', (e) => {
        e.preventDefault();
        e.stopPropagation();
        this.selectFlowNode(node, flowItem);
        this.playFlowNode(node);
      });
      
      flowList.appendChild(flowItem);
    });
  }

  switchTab(tabName) {
    this.activeTab = tabName;
    
    // 更新Tab状态
    document.querySelectorAll('.nav-item').forEach(tab => {
      tab.setAttribute('aria-selected', 'false');
    });
    document.querySelector(`.nav-item[data-tab="${tabName}"]`).setAttribute('aria-selected', 'true');
    
    // 显示对应内容
    document.querySelectorAll('.tab-content').forEach(content => {
      content.style.display = 'none';
    });
    document.getElementById(`${tabName}-tab`).style.display = 'block';
    
    // 如果是聊天tab，滚动到底部
    if (tabName === 'chat') {
      this.scrollToBottom();
    }
    
    // 清除未读消息计数
    if (window.enhancedInteractions) {
      window.enhancedInteractions.clearUnreadCount(tabName);
    }
  }

  selectFlowNode(node, flowItem) {
    // 移除之前选中项的样式
    const previousSelected = document.querySelector('.flow-item.selected');
    if (previousSelected) {
      previousSelected.classList.remove('selected');
    }
    
    // 添加选中样式到当前项
    flowItem.classList.add('selected');
    this.selectedFlowNode = node;
    
    console.log('Selected flow node:', node);
  }

  playFlowNode(node) {
    if (this.room) {
      // 参考 livekitManager/message.ts 中的 DataCommand.PLAY_FLOW_NODE
      const message = {
        command: 'play_flow_node',
        data: {
          nodeId: node.id,
          nodeName: node.name,
          projectId: this.projectId
        },
        // timestamp: Date.now()
      };
      
      // 使用标准的topic和options格式发送控制器命令
      const options = {
        topic: 'controller_command', // 参考 DataTopic.CONTROLLER_COMMAND
        reliable: true,
        type:'topic'
      };
      
      this.sendControllerMessage(message, options, true);
      this.addSystemMessage(`已发送播放指令: ${node.name}`);
    }
  }

  sendChatMessage() {
    const input = document.getElementById('messageInput');
    const message = input.value.trim();
    
    if (!message || !this.room) return;
    
     // 参考 livekitManager/message.ts 中的 DataCommand.PLAY_FLOW_NODE
    const messagedata = {
      command: 'text_chat',
      data: {
        message: message,
      },
      // timestamp: Date.now()
    };
    
    // 使用标准的topic和options格式发送控制器命令
    const options = {
      topic: 'controller_command', // 参考 DataTopic.CONTROLLER_COMMAND
      reliable: true,
      type:'topic'
    };
    
    this.sendControllerMessage(messagedata, options, true);
    this.addMessage(message, 'sent');
    input.value = '';
  }

  // 参考 livekitManager/message.ts 的 sendMessage 函数实现
  sendControllerMessage(jmessage, options = {}, isTopic = false) {
    if (!this.room) return;
    
    const timestamp = Date.now();
    let message;
    
    if (typeof jmessage === 'string') {
      message = jmessage;
    } else {
      message = JSON.stringify(jmessage);
    }
    
    let stringMessage;
    if (isTopic) {
      stringMessage = message;
    } else {
      const id = new Date().getTime().toString();
      const sendMessage = {
        timestamp,
        message,
        id
      };
      stringMessage = JSON.stringify(sendMessage);
    }
    
    // 设置默认options
    const publishOptions = {
      reliable: true,
      type:'topic',
      topic: options.topic || undefined
    };
    
    const msg = new TextEncoder().encode(stringMessage);
    this.room.localParticipant.publishData(msg, options);
    console.log('发送消息:', stringMessage);
  }

  handleDataMessage(payload, participant, kind, topic) {
    try {
      const data = JSON.parse(new TextDecoder().decode(payload));
      console.log('收到消息:', data, 'topic:', topic);
      
      // 根据topic处理不同类型的消息
      if (topic === 'lk-chat-topic') {
        this.handleChatMessage(data, participant);
      } else if (topic === 'lk-chat-update-topic') {
        this.handleChatUpdateMessage(data, participant);
      } else if (topic === 'STT') {
        this.handleSTTMessage(data, participant);
      }
     } catch (error) {
      console.error('解析消息失败:', error);
    }
  }

  handlePreviewStatus(data) {
    console.log('预览端状态:', data);
    this.addSystemMessage(`预览端状态: ${data.status}`);
  }

  handleFlowNodeCompleted(data) {
    this.addSystemMessage(`流程节点已播放完成: ${data.nodeName}`);
  }

  addMessage(content, type, from = null, messageData = null) {
    const message = {
      id: Date.now(),
      content,
      type,
      from: from || (type === 'sent' ? 'controller' : 'agent'),
      time: new Date().toLocaleTimeString('zh-CN', { 
        hour: '2-digit', 
        minute: '2-digit' 
      }),
      timestamp: Date.now(),
      messageData: messageData // 存储原始消息数据
    };
    
    this.messages.push(message);
    this.saveChatHistory(); // 保存聊天记录
    this.renderMessages();
    
    if (this.activeTab === 'chat') {
      this.scrollToBottom();
    }
  }

  addSystemMessage(content) {
    this.addMessage(content, 'system');
  }

  // 处理聊天消息
  handleChatMessage(data, participant) {
    const from = participant ? participant.identity : 'agent';
    console.log('聊天消息:', data, 'from:', from);
    
    if (from === 'agent') {
      const message = this.unicodeToString(data.message);
      
      // 过滤特殊标记
      if (message.indexOf('<|INTERRUPT|>') > -1) {
        // this.addSystemMessage('对话被打断');
        return;
      }
      
      if (message.indexOf('<|STT|>') > -1) {
        return; // 忽略STT消息
      }
      
      // 处理思考消息
      if (message.indexOf('<think>') > -1) {
        this.addMessage(message, 'think', from, data);
      } else {
        this.addMessage(message, 'received', from, data);
      }
    } else {
      // this.addMessage(data.message, 'received', from, data);
    }
  }

  // 处理聊天更新消息
  handleChatUpdateMessage(data, participant) {
    const from = participant ? participant.identity : 'agent';
    console.log('聊天更新消息:', data, 'from:', from);
    
    const message = this.unicodeToString(data.message);
    
    if (message.indexOf('<|INTERRUPT|>') > -1) {
      return;
    }
    
    if (message.indexOf('<think>') > -1) {
      this.updateLastMessage(message, 'think');
    } else {
      this.updateLastMessage(message, 'received');
    }
  }

  // 处理用户asr数据
  handleSTTMessage(data, participant) {
    console.log('STT消息:', data);
    
    // 解码消息内容
    let message = '';
    if (typeof data === 'string') {
      message = data;
    } else if (data.message) {
      message = data.message;
    } else {
      message = JSON.stringify(data);
    }
    
    // 去除末尾的中文标点符号，参考Vue组件的实现
    const cleanMessage = message.replace(/[\u3002\uff1b\uff0c\u3001\uff0e\u2026\u201c\u201d\u2018\u2019]\s*$/, '');
    
    // 添加到聊天显示
    this.addMessage(cleanMessage, 'sent');
    
    // 添加系统消息提示
    this.addSystemMessage(`语音识别: ${cleanMessage}`);
  }

  // 处理流程节点数据
  handleFlowNodeData(data, participant) {
    console.log('流程节点数据:', data);
    
    if (data.data && data.data[0] && data.data[0].sleepWord) {
      this.addSystemMessage('数字人进入睡眠状态');
      return;
    }
    
    const type = data.type;
    if (type === 'static') {
      this.addSystemMessage(`播放静态流程节点: ${data.data[0].id}`);
    } else if (type === 'dynamic') {
      this.addSystemMessage('播放动态TTS内容');
    }
  }

  // 更新最后一条消息
  updateLastMessage(content, type) {
    if (this.messages.length > 0) {
      const lastMessage = this.messages[this.messages.length - 1];
      if (lastMessage.type === type || lastMessage.type === 'received') {
        lastMessage.content = content;
        lastMessage.time = new Date().toLocaleTimeString('zh-CN', { 
          hour: '2-digit', 
          minute: '2-digit' 
        });
        this.renderMessages();
        this.saveChatHistory();
      }
    }
  }

  // Unicode转字符串
  unicodeToString(str) {
    return str.replace(/\\u[\dA-F]{4}/gi, function (match) {
      return String.fromCharCode(parseInt(match.replace(/\\u/g, ''), 16));
    });
  }

  // 保存聊天记录
  saveChatHistory() {
    // 已禁用本地聊天记录存储 - 每次打开都是新的聊天记录
    // try {
    //   const chatHistory = {
    //     projectId: this.projectId,
    //     roomName: this.roomName,
    //     messages: this.messages,
    //     timestamp: Date.now()
    //   };
    //   localStorage.setItem(`chat_history_${this.projectId}`, JSON.stringify(chatHistory));
    // } catch (error) {
    //   console.error('保存聊天记录失败:', error);
    // }
  }

  // 加载聊天记录
  loadChatHistory() {
    // 已禁用本地聊天记录加载 - 每次打开都是新的聊天记录
    // try {
    //   const saved = localStorage.getItem(`chat_history_${this.projectId}`);
    //   if (saved) {
    //     const chatHistory = JSON.parse(saved);
    //     this.messages = chatHistory.messages || [];
    //     this.renderMessages();
    //     console.log('已加载聊天记录:', this.messages.length, '条消息');
    //   }
    // } catch (error) {
    //   console.error('加载聊天记录失败:', error);
    // }
    
    // 确保每次都是空的聊天记录
    this.messages = [];
    this.renderMessages();
    console.log('已初始化新的聊天记录');
  }

  // 清空聊天记录
  clearChatHistory() {
    this.messages = [];
    this.renderMessages();
    // localStorage.removeItem(`chat_history_${this.projectId}`); // 已禁用本地存储
    this.addSystemMessage('聊天记录已清空');
  }

  renderMessages() {
    const chatMessages = document.getElementById('chatMessages');
    chatMessages.innerHTML = '';
    
    this.messages.forEach(message => {
      const isUser = message.from === 'controller';
      const isSystem = message.type === 'system';
      
      // 创建消息容器
      const messageEl = document.createElement('div');
      messageEl.className = `message-container ${isUser ? 'user-message' : 'agent-message'} ${isSystem ? 'system-message' : ''}`;
      
      // 设置头像和名称
      let avatarHtml = '';
      let nameHtml = '';
      
      if (isUser) {
        avatarHtml = `<div class="avatar user-avatar">👤</div>`;
        nameHtml = `<div class="message-name">用户</div>`;
      } else if (message.from === 'agent') {
        avatarHtml = `<div class="avatar agent-avatar">🤖</div>`;
        nameHtml = `<div class="message-name">AI助手</div>`;
      } else {
        avatarHtml = `<div class="avatar system-avatar">ℹ️</div>`;
        nameHtml = `<div class="message-name">系统</div>`;
      }
      
      // 根据消息类型显示不同的内容
      let contentHtml = '';
      
      if (message.type === 'think') {
        contentHtml = `
          <div class="message-bubble think-bubble">
            <span class="think-label">🤔 思考中...</span>
            <div class="think-text">${message.content}</div>
          </div>
        `;
      } else if (isSystem) {
        // 系统消息使用类似时间消息的样式，但更突出
        contentHtml = `
          <div class="system-notification">
            <span class="system-icon">ℹ️</span>
            <span class="system-text">${message.content}</span>
          </div>
        `;
      } else {
        contentHtml = `
          <div class="message-bubble ${isUser ? 'user-bubble' : 'agent-bubble'}">
            ${message.content}
          </div>
        `;
      }
      
      // 组装消息元素 - 系统消息居中显示，用户消息右对齐，agent消息左对齐
      if (isSystem) {
        // 系统消息使用简化的结构，不显示头像和时间
        messageEl.className = 'system-message-container';
        messageEl.innerHTML = contentHtml;
      } else if (isUser) {
        messageEl.innerHTML = `
         <div class="message-time">${message.time}</div>
          <div class="message-content-wrapper user-content-wrapper">
          <div class="avatar-wrapper user-avatar-wrapper">
              ${avatarHtml}
              ${nameHtml}
            </div>
            ${contentHtml}
            
          </div>
         
        `;
      } else {
        messageEl.innerHTML = `
        <div class="message-time">${message.time}</div>
          <div class="message-content-wrapper agent-content-wrapper">
            <div class="avatar-wrapper agent-avatar-wrapper">
              ${avatarHtml}
              ${nameHtml}
            </div>
            ${contentHtml}
          </div>
          
        `;
      }
      
      chatMessages.appendChild(messageEl);
    });
  }

  scrollToBottom() {
    setTimeout(() => {
      const chatMessages = document.getElementById('chatMessages');
      chatMessages.scrollTop = chatMessages.scrollHeight;
    }, 100);
  }

  async startRecording() {
    const micButton = document.getElementById('micButton');
    micButton.classList.add('recording');
    
    // 直接启用麦克风，参考 livekitManager/index.vue#L1199
    if (this.room && this.room.localParticipant) {
      try {
        await this.room.localParticipant.setMicrophoneEnabled(true);
        console.log('开始录音...');
      } catch (error) {
        console.error('启用麦克风失败:', error);
        micButton.classList.remove('recording');
      }
    }
  }

  async stopRecording() {
    const micButton = document.getElementById('micButton');
    micButton.classList.remove('recording');
    
    // 直接禁用麦克风，参考 livekitManager/index.vue#L1199
    if (this.room && this.room.localParticipant) {
      try {
        await this.room.localParticipant.setMicrophoneEnabled(false);
        console.log('停止录音');
      } catch (error) {
        console.error('禁用麦克风失败:', error);
      }
    }
  }

  showConnecting() {
    document.getElementById('connecting').style.display = 'flex';
  }

  hideConnecting() {
    document.getElementById('connecting').style.display = 'none';
  }

  showError(message) {
    const connecting = document.getElementById('connecting');
    connecting.innerHTML = `
      <div style="text-align: center;">
        <div style="font-size: 48px; margin-bottom: 16px;">❌</div>
        <div>${message}</div>
        <button onclick="location.reload()" style="margin-top: 16px; padding: 8px 16px; background: #007AFF; color: white; border: none; border-radius: 4px;">
          重试
        </button>
      </div>
    `;
  }
}

// 初始化应用
document.addEventListener('DOMContentLoaded', () => {
  window.controllerApp = new ControllerApp();
});

// 防止页面缩放
document.addEventListener('gesturestart', (e) => {
  e.preventDefault();
});

document.addEventListener('dblclick', (e) => {
  e.preventDefault();
});

// 防止长按菜单
window.addEventListener('contextmenu', (e) => {
  e.preventDefault();
});